package com.cskaoyan.day01.linkdemo;

/**
 * 查找中间结点
 * @author stone
 * @date 2022/01/27 14:37
 */
public class LinkedDemo2 {

    public static void main(String[] args) {
        Node node1 = new Node("红");
        Node node2 = new Node("橙");
        Node node3 = new Node("黄");
        Node node4 = new Node("绿");
        Node node5 = new Node("青");
        Node node6 = new Node("蓝");
        Node node7 = new Node("紫");

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;

        Node midNode = getMiddle(node1);
        System.out.println("中间结点的值：" + midNode.value);
    }

    private static Node getMiddle(Node head) {
        Node fast = head;
        Node slow = head;
        //alt + shift + ↑或↓

        //遍历的条件 → 最后结点或倒数第二个结点
        while (fast.next != null && fast.next.next != null) {
            //位移的代码
            slow = slow.next;
            fast = fast.next.next;
        }
        /*while (true) {
            if (fast.next == null || fast.next.next == null) {
                break;
            }
        }*/
        return slow;

    }
}
